package com.ys.service.overseas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.base.TsBatchImportInfo;
import com.ys.entity.base.TsBatchImportLog;
import com.ys.entity.overseas.TosProductActive;
import com.ys.entity.overseas.TosProductActiveDescribe;
import com.ys.entity.overseas.TosProductActiveFile;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TsBatchImportLogEnum;
import com.ys.enume.overseas.TosProductActiveEnum;
import com.ys.mapper.base.BaseDiyMapper;
import com.ys.mapper.base.TsBatchImportInfoMapper;
import com.ys.mapper.base.TsBatchImportLogMapper;
import com.ys.mapper.overseas.OverseasMapper;
import com.ys.mapper.overseas.TosProductActiveDescribeMapper;
import com.ys.mapper.overseas.TosProductActiveFileMapper;
import com.ys.mapper.overseas.TosProductActiveMapper;
import com.ys.service.base.TsBatchImportLogService;
import com.ys.service.overseas.TosProductActiveService;
import com.ys.util.CheckUtil;
import com.ys.util.FileUtilYs;
import com.ys.util.ToolUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * HW商品listing库
 */
@Service("tosProductActiveService")
public class TosProductActiveServiceImpl implements TosProductActiveService {
	private static final Logger logger = LoggerFactory.getLogger(TosProductActiveServiceImpl.class);

	@Autowired
	private TosProductActiveMapper tosProductActiveMapper;

	@Autowired
	private TosProductActiveFileMapper tosProductActiveFileMapper;

	@Autowired
	private TosProductActiveDescribeMapper tosProductActiveDescribeMapper;

	@Autowired
	private OverseasMapper overseasMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private BaseDiyMapper baseDiyMapper;

	@Autowired
	private TsBatchImportLogMapper tsBatchImportLogMapper;

	@Autowired
	private TsBatchImportInfoMapper tsBatchImportInfoMapper;

	@Autowired
	private TsBatchImportLogService tsBatchImportLogService;



	private long menuId = MenuId.TOS_ProductActive;

	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TosProductActive entity = JSON.parseObject(JSON.toJSONString(params), TosProductActive.class);

		//修改HW商品listing库
		tosProductActiveMapper.update(entity);

		//保存文件表、描述表信息
		//获取配置表信息
		List<TbStaticConfig> staticConfigList = new TbStaticConfig().setKeyOne("TOS_ProductActive").queryList();
		//先删除
		overseasMapper.deleteTosProductActiveFileByTosProductActiveId(entity.getId());
		overseasMapper.deleteTosProductActiveDescribeByTosProductActiveId(entity.getId());

		//再新增
		//图片数量
		int picNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("picNum")).collect(Collectors.toList()).get(0).getName());
		//认证文件数量
		int authenticationFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("authenticationFileNum")).collect(Collectors.toList()).get(0).getName());
		//说明书文件数量
		int explainBookFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("explainBookFileNum")).collect(Collectors.toList()).get(0).getName());
		//描述字段数量
		int describeInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("describeInfoNum")).collect(Collectors.toList()).get(0).getName());
		//详情字段数量
		int detailInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("detailInfoNum")).collect(Collectors.toList()).get(0).getName());

		//新增图片
		for(int i=1;i<=picNum;i++){
			if(checkUtil.isNotNullByObject(params.get("pic"+i))){
				TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
						.setTosProductActiveId(entity.getId())
						.setFileNo(i)
						.setFilePath(params.get("pic"+i).toString())
						.setFileType(TosProductActiveEnum.fileType.PIC.value)
						.setStatus(1)
						;
				tosProductActiveFileMapper.insert(tosProductActiveFile);
			}
		}

		//新增认证文件
		for(int i=1;i<=authenticationFileNum;i++){
			if(checkUtil.isNotNullByObject(params.get("authenticationFile"+i))){
				TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
						.setTosProductActiveId(entity.getId())
						.setFileNo(i)
						.setFilePath(params.get("authenticationFile"+i).toString())
						.setFileType(TosProductActiveEnum.fileType.AUTH_FILE.value)
						.setStatus(1)
						;
				tosProductActiveFileMapper.insert(tosProductActiveFile);
			}
		}

		//新增说明书
		for(int i=1;i<=explainBookFileNum;i++){
			if(checkUtil.isNotNullByObject(params.get("explainBookFile"+i))){
				TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
						.setTosProductActiveId(entity.getId())
						.setFileNo(i)
						.setFilePath(params.get("explainBookFile"+i).toString())
						.setFileType(TosProductActiveEnum.fileType.EXPLAIN_BOOK.value)
						.setStatus(1)
						;
				tosProductActiveFileMapper.insert(tosProductActiveFile);
			}
		}


		//新增描述
		for(int i=1;i<=describeInfoNum;i++){
			if(checkUtil.isNotNullByObject(params.get("describe"+i))){
				TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
						.setTosProductActiveId(entity.getId())
						.setInfoNo(i)
						.setContentInfo(params.get("describe"+i).toString())
						.setInfoType(TosProductActiveEnum.infoType.DESCRIBE.value)
						.setStatus(1)
						;
				tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
			}
		}


		//新增详情
		for(int i=1;i<=detailInfoNum;i++){
			if(checkUtil.isNotNullByObject(params.get("detailInfo"+i))){
				TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
						.setTosProductActiveId(entity.getId())
						.setInfoNo(i)
						.setContentInfo(params.get("detailInfo"+i).toString())
						.setInfoType(TosProductActiveEnum.infoType.DETAIL.value)
						.setStatus(1)
						;
				tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
			}
		}



		return R.ok(AddDto.gotoEdit("/web/overseas/tosProductActive/toEdit?id=" + entity.getId()));
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TOS_ProductActive",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

		return backMsg;
	}


	//获取列表数据
	@Override
	public Map<String,Object> getExtraParam( Long id) throws Exception{
		return searchByOther(new TosProductActive())

				.addLeftJoin("TOS_ProductBasis B ON A.ProductCode = B.Code ")//HW商品表
				.addField("B.SignCode AS signCode")//标识编码
				.addField("B.ProductName AS productName")//商品名称

				.addLeftJoin("TOS_PlatformInformation C ON C.Id = B.PlatformId ")//平台信息维护表
				.addField("C.HwChannel AS hwChannel")//渠道
				.addField("C.PlatformCode AS platformCode")//平台
				.addField("C.HwName AS hwName")//区域
				.addField("C.RegionName AS regionName")//站点
				.addField("C.CurrencyCode AS currencyCode")//币种


				.setId(id)
				.queryFirstMap();
	}




	/**
	 * 批量导入
	 */
	@Override
	public R importInfo(String rows, Long menuId){
		try {
			List<TsBatchImportLog> list = new ArrayList<>();
			String userId = ShiroUtils.getUserId();
			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int i=0;i<detailList.size();i++){
				JSONObject info = detailList.getJSONObject(i);
				if(info!=null){
					TsBatchImportLog tsBatchImportLog = new TsBatchImportLog();
					tsBatchImportLog.setUserId(userId);
					tsBatchImportLog.setImportInfo(info.toJSONString());
					tsBatchImportLog.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductActive.value);
					tsBatchImportLog.setImportState(TsBatchImportLogEnum.ImportState.NO.value);
					tsBatchImportLog.setStatus(0);
					list.add(tsBatchImportLog);
				}
			}
			if(list.size()>0){
				baseDiyMapper.insertBatchTsBatchImportLog(list);
			}
		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}
		return R.ok("请点击“导入详情”按钮查看导入进度！");
	}



	@Override
	public void importInfoFromBatchImportLogByUser(){
		TsBatchImportInfo tsBatchImportInfo = new TsBatchImportInfo()
				.setStatus(1)
				.setImportInfoState(0)
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductActive.value)
				;
		tsBatchImportInfoMapper.insert(tsBatchImportInfo);
		baseDiyMapper.updateTsBatchImportLogInfo(ShiroUtils.getUserId(), TsBatchImportLogEnum.InfoType.TOS_ProductActive.value, tsBatchImportInfo.getId());

		List<TsBatchImportLog> logList = new TsBatchImportLog()
				.setPid(tsBatchImportInfo.getId())
				.setUserId(ShiroUtils.getUserId())
				.setInfoType(TsBatchImportLogEnum.InfoType.TOS_ProductActive.value)
				.setImportState(TsBatchImportLogEnum.ImportState.NO.value)
				.queryList();
		if(logList!=null && logList.size()>0){
			for(TsBatchImportLog tsBatchImportLog:logList){
				addByOne(tsBatchImportLog);
			}
		}
		int importInfoState = 1;
		int count = new TsBatchImportLog().setPid(tsBatchImportInfo.getId()).setImportState(TsBatchImportLogEnum.ImportState.FAIL.value).count();
		if(count>0){
			importInfoState = 2;
		}
		TsBatchImportInfo infoByUpdate = new TsBatchImportInfo().setId(tsBatchImportInfo.getId()).setImportInfoState(importInfoState);
		tsBatchImportInfoMapper.update(infoByUpdate);
	}



	public void addByOne(TsBatchImportLog tsBatchImportLog){

		try {
			//获取所有的精品库信息
			List<TosProductActive> oldList = new TosProductActive().queryList();

			//获取配置表信息
			List<TbStaticConfig> staticConfigList = new TbStaticConfig().setKeyOne("TOS_ProductActive").queryList();

			String importInfo = tsBatchImportLog.getImportInfo();
			JSONObject info = JSONObject.parseObject(importInfo);
			Map<String, Object> infoMap = new HashMap<>();
			for (String key : info.keySet()) {
				infoMap.put(key, info.get(key)!=null?info.get(key).toString().trim():info.get(key));
			}

			StringBuilder errorMsg = new StringBuilder();


			String backMsg = checkParams(infoMap, menuId);
			if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,backMsg);
				return;
			}
			//验证商品编码
			if(info.get("productCode")==null || "".equals(info.get("productCode"))){
				logger.error("商品编码为空");
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,"商品编码为空");
				return;
			}
			List<TosProductActive> oldListByCode = oldList.stream().filter(item->item.getProductCode().equals(info.get("productCode").toString())).collect(Collectors.toList());
			if(oldListByCode.size()<=0){
				logger.error("商品编码"+info.get("productCode")+"有误");
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,"商品编码"+info.get("productCode")+"有误");
				return;
			}

			//导入商品类目
			if(checkUtil.isNotNullByObject(info.get("typeLevel").toString().trim())){
				String typeSplitChar = staticConfigList.stream().filter(e->e.getKeyTwo().equals("typeSplitChar")).collect(Collectors.toList()).get(0).getName();

				String[] typeLevelArr = info.get("typeLevel").toString().trim().split(typeSplitChar);
				if(typeLevelArr.length>=1) infoMap.put("typeLevelOne",typeLevelArr[0]);
				if(typeLevelArr.length>=2) infoMap.put("typeLevelTwo",typeLevelArr[1]);
				if(typeLevelArr.length>=3) infoMap.put("typeLevelThree",typeLevelArr[2]);
				if(typeLevelArr.length>=4) infoMap.put("typeLevelFour",typeLevelArr[3]);
				if(typeLevelArr.length>=5) infoMap.put("typeLevelFive",typeLevelArr[4]);
				if(typeLevelArr.length>=6) infoMap.put("typeLevelSix",typeLevelArr[5]);
			}

			//图片数量
			int picNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("picNum")).collect(Collectors.toList()).get(0).getName());
			//认证文件数量
			int authenticationFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("authenticationFileNum")).collect(Collectors.toList()).get(0).getName());
			//说明书文件数量
			int explainBookFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("explainBookFileNum")).collect(Collectors.toList()).get(0).getName());
			//描述字段数量
			int describeInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("describeInfoNum")).collect(Collectors.toList()).get(0).getName());
			//详情字段数量
			int detailInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("detailInfoNum")).collect(Collectors.toList()).get(0).getName());

			infoMap.put("id",oldListByCode.get(0).getId());

			TosProductActive entity = JSON.parseObject(JSON.toJSONString(infoMap), TosProductActive.class);
			//编辑
			tosProductActiveMapper.update(entity);


			//保存文件表、描述表信息
			//先删除
			overseasMapper.deleteTosProductActiveFileByTosProductActiveId(entity.getId());
			overseasMapper.deleteTosProductActiveDescribeByTosProductActiveId(entity.getId());

			//再新增

			try {
				//新增图片
				for(int i=1;i<=picNum;i++){
					if(checkUtil.isNotNullByObject(info.get("pic"+i))){
						String pathStr = uploadFileToMy(info,"pic"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.PIC.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}

				//新增认证文件
				for(int i=1;i<=authenticationFileNum;i++){
					if(checkUtil.isNotNullByObject(info.get("authenticationFile"+i))){
						String pathStr = uploadFileToMy(info,"authenticationFile"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.AUTH_FILE.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}

				//新增说明书
				for(int i=1;i<=explainBookFileNum;i++){
					if(checkUtil.isNotNullByObject(info.get("explainBookFile"+i))){
						String pathStr = uploadFileToMy(info,"explainBookFile"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.EXPLAIN_BOOK.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}

			}catch (IOException e){
				logger.error("上传文件出错：",e.getMessage(),e);
				tsBatchImportLogService.updateErrorReason(tsBatchImportLog,e.getMessage());
				return;
			}



			//新增描述
			for(int i=1;i<=describeInfoNum;i++){
				if(checkUtil.isNotNullByObject(info.get("describe"+i))){
					TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
							.setTosProductActiveId(entity.getId())
							.setInfoNo(i)
							.setContentInfo(info.get("describe"+i).toString())
							.setInfoType(TosProductActiveEnum.infoType.DESCRIBE.value)
							.setStatus(1)
							;
					tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
				}
			}


			//新增详情
			for(int i=1;i<=detailInfoNum;i++){
				if(checkUtil.isNotNullByObject(info.get("detailInfo"+i))){
					TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
							.setTosProductActiveId(entity.getId())
							.setInfoNo(i)
							.setContentInfo(info.get("detailInfo"+i).toString())
							.setInfoType(TosProductActiveEnum.infoType.DETAIL.value)
							.setStatus(1)
							;
					tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
				}
			}
			
			//修改成功标识
			TsBatchImportLog logByUpdate = new TsBatchImportLog();
			logByUpdate.setId(tsBatchImportLog.getId());
			logByUpdate.setImportState(TsBatchImportLogEnum.ImportState.SUCCESS.value);
			tsBatchImportLogMapper.update(logByUpdate);

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			tsBatchImportLogService.updateErrorReason(tsBatchImportLog,e.getMessage());
		}

	}






	/**
	 * 批量导入
	 */
	/*
	@Override
	public R importInfo(String rows,Long menuId){
		logger.info("HW商品listing导入的数据：\n"+rows);
		try {
			//获取所有的精品库信息
			List<TosProductActive> oldList = new TosProductActive().queryList();

			//获取配置表信息
			List<TbStaticConfig> staticConfigList = new TbStaticConfig().setKeyOne("TOS_ProductActive").queryList();


			StringBuilder errorMsg = new StringBuilder();

			//获取导入数据
			JSONArray detailList = JSON.parseArray(rows);
			for(int j=0;j<detailList.size();j++){
				JSONObject info = detailList.getJSONObject(j);

				Map<String, Object> infoMap = new HashMap<>();
				for (String key : info.keySet()) {
					infoMap.put(key, info.get(key)!=null?info.get(key).toString().trim():info.get(key));
				}
				//Map infoMap = JSONObject.parseObject(info.toString(), Map.class);
				//验证导入字段

				String backMsg = checkParams(infoMap, menuId);
				if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
					logger.error("第"+(j+1)+"条数据导入有误：\n"+backMsg);
					errorMsg.append("第"+(j+1)+"条数据导入有误：\n"+backMsg);
					//return R.error("第"+(i+1)+"条数据导入有误：\n"+backMsg);
					continue;
				}
				//验证商品编码
				if(info.get("productCode")==null || "".equals(info.get("productCode"))){
					logger.error("第"+(j+1)+"条数据商品编码为空");
					//return R.error("第"+(i+1)+"条数据商品编码为空");
					errorMsg.append("第"+(j+1)+"条数据商品编码为空\n");
					continue;
				}
				List<TosProductActive> oldListByCode = oldList.stream().filter(item->item.getProductCode().equals(info.get("productCode").toString())).collect(Collectors.toList());
				if(oldListByCode.size()<=0){
					logger.error("商品编码"+info.get("productCode")+"有误");
					errorMsg.append("商品编码"+info.get("productCode")+"有误\n");
					continue;
				}

				//导入商品类目
				if(checkUtil.isNotNullByObject(info.get("productCode").toString().trim())){
					String typeSplitChar = staticConfigList.stream().filter(e->e.getKeyTwo().equals("typeSplitChar")).collect(Collectors.toList()).get(0).getName();

					String[] typeLevelArr = info.get("productCode").toString().trim().split(typeSplitChar);
					if(typeLevelArr.length>=1) infoMap.put("typeLevelOne",typeLevelArr[0]);
					if(typeLevelArr.length>=2) infoMap.put("typeLevelTwo",typeLevelArr[1]);
					if(typeLevelArr.length>=3) infoMap.put("typeLevelThree",typeLevelArr[2]);
					if(typeLevelArr.length>=4) infoMap.put("typeLevelFour",typeLevelArr[3]);
					if(typeLevelArr.length>=5) infoMap.put("typeLevelFive",typeLevelArr[4]);
					if(typeLevelArr.length>=6) infoMap.put("typeLevelSix",typeLevelArr[5]);
				}

				//图片数量
				int picNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("picNum")).collect(Collectors.toList()).get(0).getName());
				//认证文件数量
				int authenticationFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("authenticationFileNum")).collect(Collectors.toList()).get(0).getName());
				//说明书文件数量
				int explainBookFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("explainBookFileNum")).collect(Collectors.toList()).get(0).getName());
				//描述字段数量
				int describeInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("describeInfoNum")).collect(Collectors.toList()).get(0).getName());
				//详情字段数量
				int detailInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("detailInfoNum")).collect(Collectors.toList()).get(0).getName());

				infoMap.put("id",oldListByCode.get(0).getId());

				TosProductActive entity = JSON.parseObject(JSON.toJSONString(infoMap), TosProductActive.class);
				//编辑
				tosProductActiveMapper.update(entity);


				//保存文件表、描述表信息
				//先删除
				overseasMapper.deleteTosProductActiveFileByTosProductActiveId(entity.getId());
				overseasMapper.deleteTosProductActiveDescribeByTosProductActiveId(entity.getId());

				//再新增

				//新增图片
				for(int i=1;i<=picNum;i++){
					if(checkUtil.isNotNullByObject(info.get("pic"+i))){
						String pathStr = uploadFileToMy(info,"pic"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.PIC.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}

				//新增认证文件
				for(int i=1;i<=authenticationFileNum;i++){
					if(checkUtil.isNotNullByObject(info.get("authenticationFile"+i))){
						String pathStr = uploadFileToMy(info,"authenticationFile"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.AUTH_FILE.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}

				//新增说明书
				for(int i=1;i<=explainBookFileNum;i++){
					if(checkUtil.isNotNullByObject(info.get("explainBookFile"+i))){
						String pathStr = uploadFileToMy(info,"explainBookFile"+i);
						TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
								.setTosProductActiveId(entity.getId())
								.setFileNo(i)
								.setFilePath(pathStr)
								.setFileType(TosProductActiveEnum.fileType.EXPLAIN_BOOK.value)
								.setStatus(1)
								;
						tosProductActiveFileMapper.insert(tosProductActiveFile);
					}
				}


				//新增描述
				for(int i=1;i<=describeInfoNum;i++){
					if(checkUtil.isNotNullByObject(info.get("describe"+i))){
						TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
								.setTosProductActiveId(entity.getId())
								.setInfoNo(i)
								.setContentInfo(info.get("describe"+i).toString())
								.setInfoType(TosProductActiveEnum.infoType.DESCRIBE.value)
								.setStatus(1)
								;
						tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
					}
				}


				//新增详情
				for(int i=1;i<=detailInfoNum;i++){
					if(checkUtil.isNotNullByObject(info.get("detailInfo"+i))){
						TosProductActiveDescribe tosProductActiveDescribe = new TosProductActiveDescribe()
								.setTosProductActiveId(entity.getId())
								.setInfoNo(i)
								.setContentInfo(info.get("detailInfo"+i).toString())
								.setInfoType(TosProductActiveEnum.infoType.DETAIL.value)
								.setStatus(1)
								;
						tosProductActiveDescribeMapper.insert(tosProductActiveDescribe);
					}
				}

			}

			if(errorMsg.length()>0){
				return R.error(errorMsg.toString());
			}

		}catch (Exception e){
			logger.error("导入出错：",e.getMessage(),e);
			return R.error("导入出错,请稍后重试!");
		}


		return R.ok("导入成功！");
	}

	 */

	public String uploadFileToMy(JSONObject info,String code)throws Exception{
		if(checkUtil.isNotNullByObject(info.get(code))){
			String imgPath = info.get(code).toString();
			String[] parts = StringUtils.split(imgPath, "?");
			R res = FileUtilYs.uploadFileByUrl(parts[0]);
			String filePath = res.get("data").toString();
			return filePath;
		}else {
			return "";
		}
	}


	/**
	 * 批量导入图片
	 */
	@Override
	public R saveImgByBatch(JSONArray detailJA)throws Exception{
		logger.info("HW商品listing批量导入图片的数据：\n"+detailJA);

		List<Map<String, Object>> imgList = ToolUtil.jsonArrayToList(detailJA);
		//根据商品编码去重
		List<Map<String, Object>> imgListGroupByCode = ToolUtil.groupsByList(imgList,e->e.get("code").toString());

		//获取配置表信息
		List<TbStaticConfig> staticConfigList = new TbStaticConfig().setKeyOne("TOS_ProductActive").queryList();
		//图片数量
		int picNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("picNum")).collect(Collectors.toList()).get(0).getName());


		if(imgListGroupByCode!=null && imgListGroupByCode.size()>0){
			//获取所有的HW商品listing库信息
			List<TosProductActive> activeList = new TosProductActive().queryList();
			if(activeList!=null && activeList.size()>0){
				//遍历导入信息中所有的商品编码
				for(Map<String, Object> codeItem:imgListGroupByCode){
					String code = codeItem.get("code").toString();//商品编码
					//获取导入数据中 对应商品编码的信息
					List<Map<String, Object>> imgListByCode = imgList.stream().filter(e->e.get("code").toString().equals(code)).collect(Collectors.toList());
					//获取原数据 对应商品编码的信息
					List<TosProductActive> activeListByCode = activeList.stream().filter(e->e.getProductCode().equals(code)).collect(Collectors.toList());
					if(activeListByCode.size()>0 && imgListByCode.size()>0){
						TosProductActive entity = activeListByCode.get(0);
						saveImg(entity,imgListByCode,picNum);
						tosProductActiveMapper.update(entity);
					}
				}
			}
		}

		return R.ok("导入成功！");
	}

	//保存图片信息
	public void saveImg(TosProductActive entity,List<Map<String, Object>> imgListByCode,int picNum){
		//先删除原本的
		overseasMapper.deleteTosProductActiveFileByTosProductActiveIdAndFileType(entity.getId(),TosProductActiveEnum.fileType.PIC.value);
		for(int row=1;row<=picNum;row++){
			if(imgListByCode.size()>=row){
				Map<String, Object> imgItem = imgListByCode.get(row-1);
				String filePath = imgItem.get("filePath")!=null?imgItem.get("filePath").toString():null;
				TosProductActiveFile tosProductActiveFile = new TosProductActiveFile()
						.setTosProductActiveId(entity.getId())
						.setFileNo(row)
						.setFilePath(filePath)
						.setFileType(TosProductActiveEnum.fileType.PIC.value)
						.setStatus(1)
						;
				tosProductActiveFileMapper.insert(tosProductActiveFile);
			}
		}

	}

	/**
	 * 查询sql设置
	 */
	@Override
	public TosProductActive searchByOther(TosProductActive cond)throws Exception{
		//获取配置表信息
		List<TbStaticConfig> staticConfigList = new TbStaticConfig().setKeyOne("TOS_ProductActive").queryList();
		//图片数量
		int picNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("picNum")).collect(Collectors.toList()).get(0).getName());
		//认证文件数量
		int authenticationFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("authenticationFileNum")).collect(Collectors.toList()).get(0).getName());
		//说明书文件数量
		int explainBookFileNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("explainBookFileNum")).collect(Collectors.toList()).get(0).getName());
		//描述字段数量
		int describeInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("describeInfoNum")).collect(Collectors.toList()).get(0).getName());
		//详情字段数量
		int detailInfoNum = Integer.parseInt(staticConfigList.stream().filter(e->e.getKeyTwo().equals("detailInfoNum")).collect(Collectors.toList()).get(0).getName());

		//查询图片
		for(int i=1;i<=picNum;i++){
			cond.addLeftJoin("TOS_ProductActiveFile PF"+i+" ON PF"+i+".TosProductActiveId = A.Id AND PF"+i+".FileNo="+i +"AND PF"+i+".FileType="+TosProductActiveEnum.fileType.PIC.value );//HW商品listing库文件信息
			cond.addField("PF"+i+".FilePath AS pic"+i);
		}
		//查询认证文件
		for(int i=1;i<=authenticationFileNum;i++){
			cond.addLeftJoin("TOS_ProductActiveFile PAF"+i+" ON PAF"+i+".TosProductActiveId = A.Id AND PAF"+i+".FileNo="+i +"AND PAF"+i+".FileType="+TosProductActiveEnum.fileType.AUTH_FILE.value );//HW商品listing库文件信息
			cond.addField("PAF"+i+".FilePath AS authenticationFile"+i);
		}
		//查询说明书文件
		for(int i=1;i<=explainBookFileNum;i++){
			cond.addLeftJoin("TOS_ProductActiveFile PEF"+i+" ON PEF"+i+".TosProductActiveId = A.Id AND PEF"+i+".FileNo="+i +"AND PEF"+i+".FileType="+TosProductActiveEnum.fileType.EXPLAIN_BOOK.value );//HW商品listing库文件信息
			cond.addField("PEF"+i+".FilePath AS explainBookFile"+i);
		}

		//查询描述字段
		for(int i=1;i<=describeInfoNum;i++){
			cond.addLeftJoin("TOS_ProductActiveDescribe PDD"+i+" ON PDD"+i+".TosProductActiveId = A.Id AND PDD"+i+".InfoNo="+i +"AND PDD"+i+".InfoType="+TosProductActiveEnum.infoType.DESCRIBE.value );//HW商品listing库描述表
			cond.addField("PDD"+i+".ContentInfo AS describe"+i);
		}

		//查询详情字段
		for(int i=1;i<=detailInfoNum;i++){
			cond.addLeftJoin("TOS_ProductActiveDescribe PID"+i+" ON PID"+i+".TosProductActiveId = A.Id AND PID"+i+".InfoNo="+i +"AND PID"+i+".InfoType="+TosProductActiveEnum.infoType.DETAIL.value );//HW商品listing库描述表
			cond.addField("PID"+i+".ContentInfo AS detailInfo"+i);
		}
		return cond;
	}



}
